<template>
  <div id="staInstrSetupSeDiv">
    <Splitpanes style="height: 100%">
      <Pane size="50">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getStaInstrSetupList" @keyup="keyupEnter" @search-click="getStaInstrSetupList()"></vxe-input>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="tloading" @click="getStaInstrSetupList"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addStaInstrSetupDialog()"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteStaInstrSetup"></vxe-button>
            <!-- <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="同步" :loading="tloading" @click="sysStaInstrSetup"></vxe-button> -->

          </template>
        </vxe-toolbar>

        <div class="modulTable">
          <vxe-table ref="staInstrSetupTableRef" class="mytable-scrollbar staInstrSetupTableClazz" border="inner" align="center" height="auto" :data="staInstrSetupList" :loading="tloading" @current-change="InstrSetupRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
            <vxe-column type="checkbox" width="30"></vxe-column>
            <vxe-column type="seq" width="30"></vxe-column>
            <vxe-column field="staInstrCode" title="标准编号"> </vxe-column>
            <vxe-column field="instrCode" title="仪器代号"> </vxe-column>
            <vxe-column field="instrName" title="仪器名称"> </vxe-column>
            <vxe-column field="instrCalled" title="仪器简介"> </vxe-column>
            <vxe-column field="instrMark" title="仪器型号"> </vxe-column>
            <vxe-column field="instrClass" title="仪器类别">
              <template #default="{ row }">
                <span>{{ formatCommon(instrClassDict, row.instrClass) }}</span>
              </template>
            </vxe-column>
            <vxe-column field="instrRegister" title="仪器注册码"> </vxe-column>
            <vxe-column field="isQc" title="是否质控" width="80">
              <template #default="{ row }">
                <vxe-checkbox v-model="row.isQc"></vxe-checkbox>
              </template>
            </vxe-column>
          </vxe-table>
          <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
                'PrevJump',
                'PrevPage',
                'Number',
                'NextPage',
                'NextJump',
                'Sizes',
                'FullJump',
                'Total'
              ]" @page-change="handleSizeChange($event)"></vxe-pager>
        </div>
      </Pane>
      <Pane size="50">
        <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
          <el-tab-pane label="基础信息" name="first">
            <vxe-toolbar perfect>
              <template #buttons>
                <vxe-button type="text" class="button-blue" @click="saveStaInstrSetup('staInstrSetupFormRef')" icon="vxe-icon-square-plus" content="保存"></vxe-button>
              </template>
            </vxe-toolbar>
            <el-form ref="staInstrSetupFormRef" :model="staInstrSetupForm" :rules="staInstrSetupFormRule" class="form-input-m" label-width="100px" inline-message>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="标准编号" prop="instrCode">
                    <el-input v-model="staInstrSetupForm.staInstrCode"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所属检验组" prop="workGroup">
                    <el-select v-model="staInstrSetupForm.workGroup" filterable placeholder="请选择检验组" style="width: 200px;">
                      <el-option v-for="workGroup in workGroupList" :key="workGroup.id" :label="workGroup.name" :value="workGroup.code"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="仪器ID" prop="instrId">
                    <el-input v-model="staInstrSetupForm.instrIdNo"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="仪器代号" prop="instrCode">
                    <el-input v-model="staInstrSetupForm.instrCode"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="仪器名称" prop="instrName">
                    <el-input v-model="staInstrSetupForm.instrName" @blur="addInputCode()"></el-input> </el-form-item></el-col>
                <el-col :span="12">
                  <el-form-item label="助记符">
                    <el-input v-model="staInstrSetupForm.inputCode"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="仪器简介" prop="instrCalled">
                    <el-input v-model="staInstrSetupForm.instrCalled"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="仪器型号" prop="instrMark">
                    <el-input v-model="staInstrSetupForm.instrMark"></el-input> </el-form-item></el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="仪器类别" prop="instrClass">
                    <!-- <el-input v-model="form.instrClass" /> -->
                    <el-select v-model="staInstrSetupForm.instrClass" placeholder="请选择" style="width:200px">
                      <el-option v-for="item in instrClassDict" :key="item.code" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="仪器注册码" prop="instrRegister">
                    <el-input v-model="staInstrSetupForm.instrRegister"></el-input> </el-form-item></el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="计算机IP">
                    <el-input v-model="staInstrSetupForm.computerIp"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="安装计算机名称">
                    <el-input v-model="staInstrSetupForm.setupComputer"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="计算机MAC地址">
                    <el-input v-model="staInstrSetupForm.setupComputerMac"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="安装时间">
                    <el-date-picker v-model="staInstrSetupForm.setupInstallDate" type="datetime" placeholder="安装时间" clearable></el-date-picker> </el-form-item></el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="重装时间">
                    <el-date-picker v-model="staInstrSetupForm.setupResetDate" type="datetime" placeholder="重装时间" clearable></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否在用" prop="isUse">
                    <el-switch v-model="staInstrSetupForm.isUse" inline-prompt active-text="是" inactive-text="否" active-value="1" inactive-value="0"></el-switch>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="停用时间">
                    <el-date-picker v-model="staInstrSetupForm.instrStopDate" type="datetime" placeholder="停用时间" clearable></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="安装位置">
                    <el-input v-model="staInstrSetupForm.installDept"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="仪器用途">
                    <el-input v-model="staInstrSetupForm.instrUse"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="注册时间">
                    <el-date-picker v-model="staInstrSetupForm.instrRegisterDate" type="datetime" placeholder="注册时间" clearable></el-date-picker> </el-form-item></el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="接口代号">
                    <el-input v-model="staInstrSetupForm.interfaceCode"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="接口类型">
                    <el-input v-model="staInstrSetupForm.interfaceType"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="运行时间">
                    <el-date-picker v-model="staInstrSetupForm.runTime" type="datetime" placeholder="运行时间" clearable></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="运行ID">
                    <el-input v-model="staInstrSetupForm.runId"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="退出时间">
                    <el-date-picker v-model="staInstrSetupForm.outTime" type="datetime" placeholder="退出时间" clearable></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="运行电脑">
                    <el-input v-model="staInstrSetupForm.runComputer"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="运行电脑IP">
                    <el-input v-model="staInstrSetupForm.runComputerIp"></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="是否质控" prop="isQc">
                    <el-switch v-model="staInstrSetupForm.isQc" inline-prompt active-text="是" inactive-text="否"></el-switch>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </Pane>
    </Splitpanes>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式

defineExpose({ initPage });
let searchForm = {
  searchValue: ''
};
let tloading = ref(false); //加载状态
let activeName = ref('first');
let staInstrSetupList: any = reactive([]);
let sltStaInstrSetup: any = ref({});
// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

let staInstrSetupForm = reactive({
  id: null,
  staInstrCode: '',
  workGroup: '',
  instrCode: '',
  instrIdNo: '',
  instrName: '',
  instrMark: '',
  instrClass: '',
  instrRegister: '',
  instrRegisterDate: '',
  rptGroup: '',
  instrCalled: '',
  setupComputer: '',
  setupComputerMac: '',
  setupInstallDate: '',
  setupResetDate: '',
  instrStopDate: '',
  computerIp: '',
  installDept: '',
  instrUse: '',
  isUse: '',
  interfaceCode: '',
  interfaceType: '',
  runComputerIp: '',
  runComputer: '',
  outTime: '',
  runId: '',
  runTime: '',
  inputCode: '',
  reportGroupName: '',
  hisEmployeeCode: '',
  isQc: false,
  orgId: ''
});

let staInstrSetupFormRule = {
  instrName: [
    {
      required: true,
      message: '请输入仪器名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ],
  instrCode: [
    {
      required: true,
      message: '请输入仪器编码',
      trigger: 'blur'
    }
  ],
  staInstrCode: [
    {
      required: true,
      message: '请输入标准编号',
      trigger: 'blur'
    }
  ]
};
onMounted(() => {
  getDictItemsList();
});
function initPage() {
  getStaInstrSetupList();
}

let instrClassDict = reactive([]); //仪器大类字典
let workGroupList = reactive([]); //仪器大类字典

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['YQDL', 'JYGZZ'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const maintainTypes = dictTreeTypeItems.data.find((item) => item.code === 'YQDL');
  instrClassDict.push(...maintainTypes.detailDataList);
  const maintainStatues = dictTreeTypeItems.data.find((item) => item.code === 'JYGZZ');
  workGroupList.push(...maintainStatues.detailDataList);
}

function getStaInstrSetupList() {
  tloading.value = true;
  staInstrSetupList.length = 0; //放入数据前清空数据
  const url = '/lis/sta/staInstrSetup/findStaInstrSetupPageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue,
        pageIndex: page.currentPage,
        pageSize: page.pageSize
      }
    })
    .then((res: any) => {
      staInstrSetupList.push(...res.data.records);
      page.totalResult = res.data.total;
      const kn = staInstrSetupList.find((k) => k.id == sltStaInstrSetup.value.id);
      if (isEmpty(kn)) {
        InstrSetupRowClick({ row: staInstrSetupList[0] }); //默认选中第一条数据
      } else {
        InstrSetupRowClick({ row: kn }); //默认选中第一条数据
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function sysStaInstrSetup() {
  tloading.value = true;
  staInstrSetupList.length = 0; //放入数据前清空数据
  const url = '/lis/sta/staInstrSetup/sysStaInstrSetup';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue,
        pageIndex: page.currentPage,
        pageSize: page.pageSize
      }
    })
    .then((res: any) => {
      staInstrSetupList.push(...res.data.records);
      page.totalResult = res.data.total;
      const kn = staInstrSetupList.find((k) => k.id == sltStaInstrSetup.value.id);
      if (isEmpty(kn)) {
        InstrSetupRowClick({ row: staInstrSetupList[0] }); //默认选中第一条数据
      } else {
        InstrSetupRowClick({ row: kn }); //默认选中第一条数据
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  getStaInstrSetupList();
}

function saveStaInstrSetup(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    if (staInstrSetupForm.id === null) {
      const url = '/lis/sta/staInstrSetup/addStaInstrSetup';

      proxy.$http
        .post(url, staInstrSetupForm)
        .then((res: any) => {
          VxeMessage('新增成功', VxeNotifyType.success);
          clearForm();
          sltStaInstrSetup.value.id = res.data.id;
          getStaInstrSetupList();
        })
        .catch((err: any) => {
          VxeMessage('新增失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/lis/sta/staInstrSetup/editStaInstrSetup';

      proxy.$http
        .post(url, staInstrSetupForm)
        .then((res: any) => {
          VxeMessage('修改成功', VxeNotifyType.success);
          sltStaInstrSetup.value.id = res.data.id;
          setTimeout(() => {
            clearForm();
            getStaInstrSetupList();
          }, 50);
        })
        .catch((err: any) => {
          VxeMessage('修改失败', VxeNotifyType.error);
        });
    }
  });
}
function deleteStaInstrSetup() {
  const sltStaInstrSetups = (proxy.$refs.staInstrSetupTableRef as any).getCheckboxRecords();
  if (!(sltStaInstrSetups.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delStaInstrSetupList = sltStaInstrSetups.filter((p: any) => !isEmpty(p.id));
        if (delStaInstrSetupList.length > 0) {
          const data = { staInstrSetupList: delStaInstrSetupList };
          const url = '/lis/sta/staInstrSetup/batchDeleteStaInstrSetupList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              getStaInstrSetupList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    getStaInstrSetupList();
  }
}
// 点击设计模式表格当前行触发右侧表单变化
function InstrSetupRowClick({ row }: any) {
  if (isEmpty(row)) {
    clearForm();
    sltStaInstrSetup.value = {};
  } else {
    (proxy.$refs.staInstrSetupTableRef as any).setCurrentRow(row);
    setStaInstrSetupForm(row);
  }
}

function addStaInstrSetupDialog() {
  clearForm();
  sltStaInstrSetup.value = {};
  (proxy.$refs.staInstrSetupTableRef as any).clearCurrentRow();
  activeName.value = 'first';
}

// 清空中间规则弹框表单
function clearForm() {
  for (let key in staInstrSetupForm) {
    staInstrSetupForm[key] = '';
  }
  staInstrSetupForm.id = null;
  staInstrSetupForm.isQc = false;
}

// 编辑当前行规则
function setStaInstrSetupForm(row: any) {
  if (row !== null) {
    for (let prop in row) {
      staInstrSetupForm[prop] = row[prop];
    }
  }
  sltStaInstrSetup.value = row;
}

function tabHandleClick(tab: any) {}

function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}

// 获取是否静态的tag标记(绿/红)
function getIsTagType(row: any) {
  if (row == '1') {
    return 'success';
  } else {
    return 'danger';
  }
}
// 获取是否静态文字(是/否)
function getIsStatusDesc(row: any) {
  if (row == '1') {
    return '是';
  } else {
    return '否';
  }
}
// 填写仪器名称 自动生成助记符
function addInputCode() {
  staInstrSetupForm.inputCode = funBdsJsResult('firstPinYinFun', staInstrSetupForm.instrName);
}
const predefineColors = ref(['#ff4500', '#ff8c00', '#ffd700', '#90ee90', '#00ced1', '#1e90ff', '#c71585', 'rgba(255, 69, 0, 0.68)', 'rgb(255, 120, 0)', 'hsv(51, 100, 98)', 'hsva(120, 40, 94, 0.5)', 'hsl(181, 100%, 37%)', 'hsla(209, 100%, 56%, 0.73)', '#c7158577']);
</script>

<style lang="scss" scoped>
#staInstrSetupSeDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .modulTable {
    height: calc(100% - 40px - 30px);
    background-color: $base-white;
  }
}
</style>